const router = require('express').Router()
const md5 = require('md5')
const jwt = require('jsonwebtoken')
const { secret } = require('../config')
const { wrap } = require('../tool')
const { User } = require('../config/sql')

router.post('/login', wrap(async (req, res) => {
   const { email, password } = req.body
   if (!email || !password) throw '316'
   const [user] = await User.findAll({
      attributes: ['uid', 'nickname', 'password'],
      where: {
         email
      }
   })
   if (!user || user.password !== md5(password)) throw '322'
   res.send({
      code: 200,
      token: jwt.sign({
         data: {
            nikename: user.nickname,
            account: user.uid,
         }
      }, secret, {
         expiresIn: '7days'
      })
   })
}))
module.exports = router